const service = require('./myAddressService.js')
const noti = require('../../../utils/WxNotificationCenter.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    datas: [],
    editIndex: 0,
    delBtnWidth: wx.getSystemInfoSync().windowWidth * 0.3, //删除按钮宽度单位（rpx）
    txtStyle: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.reload()
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.reload()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  reload: function () {
    var that = this
    service.request(function (datas) {
      wx.stopPullDownRefresh()
      wx.hideLoading()
      that.setData({ datas: datas })
    })
  },

  selectItem: function (e) {
    var index = parseInt(e.currentTarget.id) - 100
    var data = this.data.datas[index]

    var pages = getCurrentPages()
    var prePage = pages[pages.length - 2]

    // var address = data.region + data.address
    wx.showLoading({
      title: '正在修改默认地址',
    })
    prePage.setData({ addressData: data, defaultAddressData: data})
    noti.postNotificationName(noti.refreshAddress)
    wx.navigateBack({
      delta: 1
    })
    // service.chooseAddress(data.id,
    //   function (result) {
    //     wx.hideLoading()
    //     wx.showToast({
    //       title: '默认地址设置成功',
    //       icon: 'success',
    //       duration: 1000
    //     })
    //     setTimeout(function () {
    //     }, 1000)

    //   },
    //   function (error) {
    //     wx.hideLoading()
    //     wx.showToast({
    //       title: '默认地址设置失败',
    //       icon: 'none',
    //       duration: 2000, 
    //       complete: function () {
    //         prePage.setData({ addressData: data })
    //         wx.navigateBack({
    //           delta: 1
    //         })
    //       }
    //     })
    //   })


  },

  editAddress: function (e) {
    var that = this
    var index = parseInt(e.currentTarget.id)
    var data = this.data.datas[index]

    wx.showActionSheet({
      itemList: ['编辑', '删除'],
      success: function(res) {
        if (res.tapIndex == 0) {

          let str = JSON.stringify(data)
          wx.navigateTo({
            url: './editAddress/editAddress?jsonStr=' + str
          })
        }else {
          that.deleteAddress(data)
        }
      }
    })

  },

  addAddress: function () {
    if (this.data.datas.length <= 0) {
      var that = this

      wx.showActionSheet({
        itemList: ['微信地址', '添加新地址'],
        success: function (res) {
          if (res.tapIndex == 0) {
            wx.chooseAddress({
              success: function (res) {

                var param = {
                  "userId": getApp().globalData.userId,
                  "name": res.userName,
                  "phone": res.telNumber,
                  "region": res.provinceName + res.cityName + res.countyName,
                  "address": res.detailInfo,
                  "zipCode": res.postalCode
                }

                that.requestAdd(param)
              }
            })
          } else {
            wx.navigateTo({
              url: './editAddress/editAddress'
            })
          }
        },
        fail: function (res) { }
      })
    } else {
      wx.navigateTo({
        url: './editAddress/editAddress'
      })
    }
  },

  deleteAddress: function (data) {
    if (data.defaultFlag == 0){
      wx.showToast({
        title: '不能删除默认地址',
        icon:"none"
      })
      return
    }
    this.requestDelete(data.id)
  },

  requestDelete: function (addressId) {
    wx.showLoading({
      title: '加载中',
    })

    var that = this
    service.requestDelete(addressId + "",
      function (data) {
        wx.hideLoading()
        wx.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 1000
        })

        setTimeout(function () {
          wx.showLoading({
            title: '数据刷新中',
          })
          that.reload()
        }, 1000)
      })
  },

  requestAdd: function (param) {
    wx.showLoading({
      title: '加载中',
    })

    var that = this
    service.requestAdd(param,
      function (data) {
        wx.hideLoading()
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 1500
        })

        setTimeout(function () {
          wx.showLoading({
            title: '数据刷新中',
          })
          that.reload()
        }, 1500)
      })
  },

  //手指刚放到屏幕触发
  touchS: function (e) {
    // this.data.currentIndex = e
    //判断是否只有一个触摸点
    if (e.touches.length == 1) {
      this.setData({
        //记录触摸起始位置的X坐标
        startX: e.touches[0].clientX
      });
    }
  },
  //触摸时触发，手指在屏幕上每移动一次，触发一次
  touchM: function (e) {
    var that = this
    if (e.touches.length == 1) {
      //记录触摸点位置的X坐标
      var moveX = e.touches[0].clientX;
      //计算手指起始点的X坐标与当前触摸点的X坐标的差值
      var disX = that.data.startX - moveX;
      //delBtnWidth 为右侧按钮区域的宽度
      var delBtnWidth = that.data.delBtnWidth;
      var txtStyle = "";
      var actionStyle = "";
      if (disX == 0 || disX < 0) {//如果移动距离小于等于0，文本层位置不变
        txtStyle = "margin-left:0px";
        actionStyle = "width:0px";
      } else if (disX > 0) {//移动距离大于0，文本层left值等于手指移动距离
        txtStyle = "margin-left:-" + disX + "px";
        actionStyle = "width:" + disX + "px";
        if (disX >= delBtnWidth) {
          //控制手指移动距离最大值为删除按钮的宽度
          txtStyle = "margin-left:-" + delBtnWidth + "px";
          actionStyle = "width:" + delBtnWidth + "px";
        }
      }
      //获取手指触摸的是哪一个item
      var index = e.currentTarget.dataset.index;
      var list = that.data.datas;
      // //将拼接好的样式设置到当前item中
      list[index].txtStyle = txtStyle;
      list[index].actionStyle = actionStyle;
      //更新列表的状态
      this.setData({
        datas: list
      });
    }
  },
  touchE: function (e) {
    var that = this
    if (e.changedTouches.length == 1) {
      //手指移动结束后触摸点位置的X坐标
      var endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离
      var disX = that.data.startX - endX;
      var delBtnWidth = that.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      var txtStyle = disX > delBtnWidth / 2 ? "margin-left:-" + delBtnWidth + "px" : "margin-left:0px";
      var actionStyle = disX > delBtnWidth / 2 ? "width:" + delBtnWidth + "px" : "margin-left:0px";
      //获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index;
      var list = that.data.datas;
      list[index].txtStyle = txtStyle;
      list[index].actionStyle = actionStyle;
      //更新列表的状态
      that.setData({
        datas: list
      });
    }
  },
})